//
//  Utilties.m
//  mendianjieke
//
//  Created by 响当当 on 7/30/19.
//  Copyright © 2019 dongzheng. All rights reserved.
//

#import "Utilties.h"
#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>
#import <dlfcn.h>
#import "CXAlertView.h"


@implementation Utilties
+ (void)monitorNetworking
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                [Utilties showAlertWithTitle:@"提示" content:@"暂无识别开启网络，是否前往设置" buttonTitle:@"确定" ConfirmWithBlock:^{
                    [Utilties openUrlSchedule:UIApplicationOpenSettingsURLString];
                }];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                [Utilties showAlertWithTitle:@"提示" content:@"暂无识别开启网络，是否前往设置" buttonTitle:@"确定" ConfirmWithBlock:^{
                    [Utilties openUrlSchedule:UIApplicationOpenSettingsURLString];
                }];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                NSLog(@"GPRS网络");
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                NSLog(@"wifi网络");
            }
                break;
            default:
                break;
        }
        
    }];
}

/**
 * 获取当前屏幕显示的viewcontroller
 */
+ (UIViewController *)getCurrentVC
{
    //获得当前活动窗口的根视图
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1)
    {
        //根据不同的页面切换方式，逐步取得最上层的viewController
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
    }
    return vc;
}

/**
 *    url跳转
 */
+ (void)openUrlSchedule:(NSString *)urlStr
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
}

//创建label
+ (UILabel *)creatLabelWithFrame:(CGRect)Rect
                    textAligment:(NSTextAlignment)textAligment
                        textClor:(UIColor *)color
                        textFont:(CGFloat)size
{
    UILabel *label = [[UILabel alloc]initWithFrame:Rect];
    label.textAlignment = textAligment;
    label.textColor = color;
    label.font = [UIFont systemFontOfSize:size];
    return label;
}

//创建button
+ (UIButton *)creatButtonWithFrame:(CGRect)Rect
                      textAligment:(UIControlContentHorizontalAlignment)textAligment
                              text:(NSString *)title
                          textClor:(UIColor *)color
                         buttonBGC:(UIColor *)bgcColor
                          textFont:(CGFloat)size
                            target:(id)vc
                            method:(SEL)method
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = Rect;
    [button setTitleColor:color forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:size]];
    [button setContentHorizontalAlignment:textAligment];
    [button setBackgroundColor:bgcColor];
    [button addTarget:vc action:method forControlEvents:UIControlEventTouchUpInside];
    return button;
}

+ (UIView *)getNoCountViewWithFrame:(CGRect)frame image:(NSString *)str title:(NSString *)text
{
    UIView *bgView = [[UIView alloc]initWithFrame:frame];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0,frame.size.width,223*kUIScaleBasePlus)];
    imageView.image = [UIImage imageNamed:str];
    [bgView addSubview:imageView];
    
    UILabel *titleLabel = [Utilties creatLabelWithFrame:CGRectMake(0,CGRectGetMaxY(imageView.frame)+15*kUIScaleBasePlus,frame.size.width,50*kUIScaleBasePlus)
                                           textAligment:NSTextAlignmentCenter
                                               textClor:LCHexColor(0xA09C9C)
                                               textFont:14*kUIScaleBasePlus];
    
    titleLabel.numberOfLines = 0;
    
    NSMutableParagraphStyle  *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle  setLineSpacing:10];
    
    NSMutableAttributedString  *setString = [[NSMutableAttributedString alloc] initWithString:text];
    [setString  addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [text length])];
    
    titleLabel.attributedText = setString;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [bgView addSubview:titleLabel];
    
    return bgView;
    
}


//电话号码
+ (BOOL)checkTel:(NSString *)mobileNumbel

{
    if (!mobileNumbel)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号码"];
        
        DISMISS_SVP(1.2f);
        
        return NO;
        
    }else{
        
        if (mobileNumbel.length == 11) {
            
            return true;
        }
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码"];
        DISMISS_SVP(1.2f);
        return false;
    }
}


//这个函数就是将字典封装成转义的JSON字符串
+ (NSString *)toJSONString:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *str = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    return str;
}

+ (void)showAlertWithTitle:(NSString *)titleStr
                   content:(NSString *)eventStr
               buttonTitle:(NSString *)btnTitle
            cancelBtnTitle:(NSString *)cancelBtnTitle
          ConfirmWithBlock:(void(^)(void))comfirm
{
    
    CXAlertView *alterview = [[CXAlertView alloc]initWithTitle:titleStr message:eventStr cancelButtonTitle:cancelBtnTitle];
    
    [alterview addButtonWithTitle:btnTitle type:CXAlertViewButtonTypeDefault handler:^(CXAlertView *alertView, CXAlertButtonItem *button) {
        [alertView dismiss];
        
        comfirm();
        
    }];
    [alterview show];
}

/*
 ** 提示操作,不含取消
 
 */
+ (void)showAlertWithTitle:(NSString *)titleStr
                   content:(NSString *)eventStr
               buttonTitle:(NSString *)btnTitle
          ConfirmWithBlock:(void(^)(void))comfirm
{
    
    CXAlertView *alterview = [[CXAlertView alloc]initWithTitle:titleStr message:eventStr cancelButtonTitle:nil];
    [alterview addButtonWithTitle:btnTitle type:CXAlertViewButtonTypeDefault handler:^(CXAlertView *alertView, CXAlertButtonItem *button) {
        [alertView dismiss];
        comfirm();
    }];
    [alterview show];
}

//时间戳转换成时间
+ (NSString *)getTime:(NSString *)time
{
    NSTimeInterval interval = [time doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [formatter stringFromDate: date];
    
    return dateString;
}

//时间
+ (NSString *)getHMS:(NSString *)time
{
    NSTimeInterval interval = [time doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm"];
    NSString *dateString = [formatter stringFromDate: date];
    
    return dateString;
}

//将字符串转成NSDate类型
+ (NSDate *)dateFromString:(NSString *)dateString
{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd"];
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    return destDate;
}

//获取上一天
+ (NSString *)getLastday:(NSDate *)lastDay
{
    NSDate *last = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:lastDay];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
       
       [formatter setDateFormat:@"yyyy"];
       NSInteger currentYear=[[formatter stringFromDate:last] integerValue];
       [formatter setDateFormat:@"MM"];
       NSInteger currentMonth=[[formatter stringFromDate:last]integerValue];
       [formatter setDateFormat:@"dd"];
       NSInteger currentDay=[[formatter stringFromDate:last] integerValue];
       
        if (currentDay < 10)
          {
              return [NSString stringWithFormat:@"%ld-%ld-0%ld",currentYear,currentMonth,currentDay];
          }
          else
          {
              return [NSString stringWithFormat:@"%ld-%ld-%ld",currentYear,currentMonth,currentDay];
          }
    
}

//获取下一天
+ (NSString *)getNextday:(NSDate *)nextDay
{
    NSDate *next = [NSDate dateWithTimeInterval:24*60*60 sinceDate:nextDay];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
       
       [formatter setDateFormat:@"yyyy"];
       NSInteger currentYear=[[formatter stringFromDate:next] integerValue];
       [formatter setDateFormat:@"MM"];
       NSInteger currentMonth=[[formatter stringFromDate:next]integerValue];
       [formatter setDateFormat:@"dd"];
       NSInteger currentDay=[[formatter stringFromDate:next] integerValue];
       
        if (currentDay < 10)
          {
              return [NSString stringWithFormat:@"%ld-%ld-0%ld",currentYear,currentMonth,currentDay];
          }
          else
          {
              return [NSString stringWithFormat:@"%ld-%ld-%ld",currentYear,currentMonth,currentDay];
          }
    
}

//获取当前年月
+ (NSString *)getYearAndMonth
{
    NSDate *date =[NSDate date];//简书 FlyElephant
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"yyyy"];
    NSInteger currentYear=[[formatter stringFromDate:date] integerValue];
    [formatter setDateFormat:@"MM"];
    NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
    [formatter setDateFormat:@"dd"];
    NSInteger currentDay=[[formatter stringFromDate:date] integerValue];
    
    if (currentDay < 10)
    {
        return [NSString stringWithFormat:@"%ld-%ld-0%ld",currentYear,currentMonth,currentDay];
    }
    else
    {
        return [NSString stringWithFormat:@"%ld-%ld-%ld",currentYear,currentMonth,currentDay];
    }
}


//获得年月日分十秒
+(NSString *)getNowTimeTimestamp
{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    
    return timeSp;
}


//字典转JSON
+(NSString *)convertJSONWithDic:(NSDictionary *)dic
{
    NSError *err;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&err];
    if (err) {
        return @"字典转JSON出错";
    }
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

//JSON转字典
+(NSDictionary *)convertDicWithJSON:(NSString *)jsonStr
{
    if (jsonStr.length == 0) {
        return nil;
    }
    NSError *err;
    NSData *jsondata = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsondata options:NSJSONReadingMutableContainers error:&err];
    if (err) {
        return nil;
    }
    
    return dic;
}

/**
 *  push web
 */
+ (void)pushWebWithUrl:(NSString *)urlStr title:(NSString *)title toUrl:(NSString *)toUrl toId:(NSString *)toId
{
    HWCommonWebViewController *tag = [[HWCommonWebViewController alloc]init];
    tag.titleStr = title;
    tag.urlStr = urlStr;
    tag.type = @"1";
    tag.hidesBottomBarWhenPushed = YES;
    
    UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (topRootViewController.presentedViewController)
    {
        topRootViewController = topRootViewController.presentedViewController;
    }
    
    [topRootViewController presentViewController:tag animated:YES completion:nil];
}

#pragma 是否第一次启动
+ (BOOL)isFirstTimeStartover
{
    // 1. 获取当前版本信息
    NSString *currentBundleVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleVersion"];
    // 2. 判断当前版本是否是最新
    if ([currentBundleVersion isEqualToString:[[NSUserDefaults standardUserDefaults] stringForKey:LCVersionKey]]) {
        return false;
    } else {
        // 1. 保存新版本信息（偏好设置)
        [[NSUserDefaults standardUserDefaults] setObject:currentBundleVersion forKey:LCVersionKey];
        return true;
    }
}

//冒泡排序
+(NSMutableArray *)BubbleSorting:(NSMutableArray *)arr
{
    NSMutableArray *result = arr;
    for (int i = 0; i<result.count-1; i++) {//外层循环控制趟数，总趟数为集合元素个数（result.count）
           for (int j = 0; j<result.count-1-i; j++) {
               NSInteger left = [result[j] integerValue];
               NSInteger right = [result[j+1] integerValue];
               if (left>right) {
                   [result exchangeObjectAtIndex:j withObjectAtIndex:j+1];
               }
           }
       }
    return result;
}
@end
